package com.example.qxfw.backgroundManagement.controller;

import com.example.qxfw.backgroundManagement.service.WorkforceManagementService;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.rcyw.pojo.JobMake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/************************************
 *
 * @author : HuangDeYin Jolly
 * @since : JDK 11
 * @Date : 2023/7/3  星期一   14:37
 * @description : 此类用来 排班管理的控制层接口
 ***************************************/
@Api(tags = "后台管理-业务管理")
@RestController
@CrossOrigin
@RequestMapping("/WorkforceManagement")
@Log4j2
public class WorkforceManagementController {

    @Autowired
    private WorkforceManagementService workforceManagementService;

    @ApiOperation("初始化列表")
    @GetMapping(value = "selectJobMark")
    public SysResult selectJobMark() {
        List<JobMake> jobMakes = this.workforceManagementService.listJobMark();
        return SysResult.success(jobMakes);
    }


    /**
     * 查找业务类型
     *
     * @return nametype
     */
    @ApiOperation("查找业务类型")
    @GetMapping(value = "selectJobType")
    public SysResult selectJobType() {
        List<JobMake> jobMakes = this.workforceManagementService.selectJobType();
        return SysResult.success(jobMakes);
    }

    @ApiOperation("根据业务类型查询业务名称")
    @GetMapping(value = "selectJobName")
    public SysResult selectJobName(final String nameType) {
        List<JobMake> jobMakes = this.workforceManagementService.selectJobName(nameType);
        return SysResult.success(jobMakes);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "nameType", value = "业务类型", dataType = "String"),
            @ApiImplicitParam(name = "jobName", value = "业务名称", dataType = "String")
    })
    @ApiOperation("根据业务类型和业务名称进行查询")
    @GetMapping(value = "selectJobNameAndJobType")
    public SysResult selectJobNameAndJobType(final String nameType, final String jobName) {
        String type = nameType;
        String name = jobName;
        if (nameType.equals("全部")) {
            type = null;
        }
        if (jobName.equals("全部")) {
            name = null;
        }
        List<JobMake> jobMakes = this.workforceManagementService.selectJobNameAndJobType(type, name);
        return SysResult.success(jobMakes);
    }

    /*因为表job_make中有效字段只是id,jobname,nametype,recentmaketime,所以这里只传这几个字段,在此作出修改*/
    @ApiOperation("添加业务信息")
    @PostMapping(value = "insertJobMark")
    public SysResult insertJobMark(@RequestBody JobMake jobMake) {
        Integer insertJobMark = this.workforceManagementService.insertJobMark(jobMake.getJobname(), jobMake.getNametype(),  jobMake.getRecentmaketime());
        return returnInformation("添加业务信息", insertJobMark);
    }

    @ApiOperation("更新业务信息")
    @PostMapping(value = "updateJobMark")
    public SysResult updateJobMark(@RequestBody JobMake jobMake) {
        log.debug(jobMake);
        Integer updateJobMark = this.workforceManagementService.updateJobMark(jobMake);
        return returnInformation("更新业务信息", updateJobMark);
    }

    @ApiOperation("删除业务信息")
    @GetMapping(value = "deleteJobMark")
    public SysResult deleteJobMark(final int id) {
        Integer deleteJobMark = this.workforceManagementService.deleteJobMark(id);
        return returnInformation("删除业务信息", deleteJobMark);
    }

    /**
     * @param
     * @return var file=$("#file").get(0).files[0];
     * var formData=new FormData();
     * formData.append("file",file);
     * $.ajax({
     * url:"/../importJobMark",
     * type:"post",
     * data:formData,
     * contentType:false,
     * processData:false,
     * success:function (data) {
     * alert(data);
     * },
     * error:function () {
     * alert("error");
     * }
     * })
     */

    @ApiOperation("导入业务信息-清除旧数据")
    @PostMapping(value = "importJobMark")
    @ResponseBody
    public SysResult importJobMark(MultipartFile file) {
        List<JobMake> jobMakelist = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();//获取前端传递过来的文件对象，存储在“inputStream”中
            String fileName = file.getOriginalFilename();//获取文件名

            Workbook workbook = null; //用于存储解析后的Excel文件

            //判断文件扩展名为“.xls还是xlsx的Excel文件”,因为不同扩展名的Excel所用到的解析方法不同
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (".xls".equals(fileType)) {
                workbook = new HSSFWorkbook(inputStream);//HSSFWorkbook专门解析.xls文件
            } else if (".xlsx".equals(fileType)) {
                workbook = new XSSFWorkbook(inputStream);//XSSFWorkbook专门解析.xlsx文件
            }

            ArrayList<ArrayList<Object>> list = new ArrayList<>();

            Sheet sheet; //工作表
            Row row;      //行
            Cell cell;    //单元格

            //循环遍历，获取数据
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                sheet = workbook.getSheetAt(i);//获取sheet
                for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {//从有数据的第行开始遍历
                    row = sheet.getRow(j);
                    if (row != null && row.getFirstCellNum() != j) { //row.getFirstCellNum()!=j的作用是去除首行，即标题行，如果无标题行可将该条件去掉
                        ArrayList tempList = new ArrayList();
                        JobMake jobMake = new JobMake();
                        for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {//这里需要注意的是getLastCellNum()的返回值为“下标+1”
                            cell = row.getCell(k);
                            tempList.add(cell);
                            if (k == 0) {
                                jobMake.setId((int) cell.getNumericCellValue());
                            } else if (k == 1) {
                                jobMake.setJobname(cell.getStringCellValue());
                            } else if (k == 2) {
                                jobMake.setNametype(cell.getStringCellValue());
                            } else if (k == 3) {
                                jobMake.setRecentmaketime(cell.getDateCellValue());
                            }
                        }
                        list.add(tempList);
                        jobMakelist.add(jobMake);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Integer importJobMark = this.workforceManagementService.importJobMark(jobMakelist);
        return returnInformation("导入业务信息", importJobMark);
    }



    @ApiOperation("导入业务信息-保留原有数据")
    @PostMapping(value = "importJobMark1")
    @ResponseBody
    public SysResult importJobMark1(MultipartFile file) {
        List<JobMake> jobMakelist = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();//获取前端传递过来的文件对象，存储在“inputStream”中
            String fileName = file.getOriginalFilename();//获取文件名

            Workbook workbook = null; //用于存储解析后的Excel文件

            //判断文件扩展名为“.xls还是xlsx的Excel文件”,因为不同扩展名的Excel所用到的解析方法不同
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (".xls".equals(fileType)) {
                workbook = new HSSFWorkbook(inputStream);//HSSFWorkbook专门解析.xls文件
            } else if (".xlsx".equals(fileType)) {
                workbook = new XSSFWorkbook(inputStream);//XSSFWorkbook专门解析.xlsx文件
            }

            ArrayList<ArrayList<Object>> list = new ArrayList<>();

            Sheet sheet; //工作表
            Row row;      //行
            Cell cell;    //单元格

            //循环遍历，获取数据
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                sheet = workbook.getSheetAt(i);//获取sheet
                for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {//从有数据的第行开始遍历
                    row = sheet.getRow(j);
                    if (row != null && row.getFirstCellNum() != j) { //row.getFirstCellNum()!=j的作用是去除首行，即标题行，如果无标题行可将该条件去掉
                        ArrayList tempList = new ArrayList();
                        JobMake jobMake = new JobMake();
                        for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {//这里需要注意的是getLastCellNum()的返回值为“下标+1”
                            cell = row.getCell(k);
                            tempList.add(cell);
                            if (k == 0) {
                                jobMake.setId((int) cell.getNumericCellValue());
                            } else if (k == 1) {
                                jobMake.setJobname(cell.getStringCellValue());
                            } else if (k == 2) {
                                jobMake.setNametype(cell.getStringCellValue());
                            } else if (k == 3) {
                                jobMake.setRecentmaketime(cell.getDateCellValue());
                            }
                        }
                        list.add(tempList);
                        jobMakelist.add(jobMake);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println(jobMakelist);
        Integer importJobMark = this.workforceManagementService.importJobMark1(jobMakelist);
        return returnInformation("导入业务信息", importJobMark);
    }
    public SysResult returnInformation(String info, Integer result) {
        if (result < 0) {
            return SysResult.fail(info + "失败");
        } else {
            return SysResult.success(result);
        }
    }
}
